<template>
  <div v-global-loading="tableLoading">
    <!-- 结算信息预览 -->
    <div
      style="margin-top: 10px; display: flex; justify-content: space-between"
    >
      <span style="font-size: 18px; font-weight: 800">商品清单</span>
      <span
        style="font-size: 14px; font-weight: 600; color: #175cab"
        class="pointer"
        @click="pressUndo"
      >
        返回上一步操作>>
      </span>
    </div>
    <a-table
      size="small"
      :dataSource="formData.products"
      :columns="columns"
      bordered
      :pagination="false"
      :scroll="{x: 700, y: 700}"
    >
      <template #bodyCell="{text, record, index, column}">
        <template v-if="column.title == '商品信息'">
          <div style="display: flex; justify-content: space-around">
            <div style="width: 150px">
              <img
                :src="record.productImg[0].ImgUrl"
                v-if="record.productImg.length"
                style="width: 150px"
                alt=""
              />
            </div>
            <div>
              <div
                style="
                  height: 75px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <span>{{ record.productName }}</span>
              </div>
              <div
                style="
                  height: 75px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <span>商品编号：{{ record.productCode }}</span>
              </div>
            </div>
          </div>
        </template>
        <template v-if="column.title == '客户物料号'">
          <a-input
            v-model:value="formData.products[index].materialNum"
          ></a-input>
        </template>
        <template v-if="column.title == '客户物料名称'">
          <a-input
            v-model:value="formData.products[index].materialName"
          ></a-input>
        </template>
        <!-- <template v-if="column.title == '客户物料规格'">
          <a-input
            v-model:value="formData.products[index].materialSpec"
          ></a-input>
        </template>
        <template v-if="column.title == '客户物料单位'">
          <a-input
            v-model:value="formData.products[index].materialUnit"
          ></a-input>
        </template>
        <template v-if="column.title == '物料数量'">
          <a-input-number
            :min="0"
            v-model:value="formData.products[index].materialCount"
          ></a-input-number>
        </template> -->
        <template v-if="column.title == '数量*单位'">
          <span>{{ text }}*{{ record.productUnit }}</span>
        </template>
        <template v-if="column.title == '含税单价(元)'">
          <span>￥{{ record.memberPrice }}</span
          ><br />
          <span
            >(不含：￥{{
              arithmetic(record.memberPrice, record.tax, "subtract") || 0
            }})</span
          >
        </template>
        <template v-if="column.title == '含税小计(元)'">
          <span style="color: red">￥{{ text }}</span>
        </template>
      </template>
    </a-table>
    <div style="font-size: 18px; font-weight: 800; margin-top: 10px">
      收货地址：
    </div>
    <a-table
      size="small"
      :dataSource="tableData1"
      :columns="columns2"
      bordered
      :pagination="false"
      row-key="id"
      :row-selection="{
        selectedRowKeys: submitDataProps.receivingAddressId,
        type: 'radio'
      }"
    >
    </a-table>
    <div style="font-size: 18px; font-weight: 800; margin-top: 10px">
      收票地址：
    </div>
    <a-table
      size="small"
      :dataSource="tableData2"
      :columns="columns3"
      bordered
      :pagination="false"
      row-key="id"
      :row-selection="{
        selectedRowKeys: submitDataProps.invoiceAddressId,
        type: 'radio'
      }"
    >
      <template #bodyCell="{text, record, index, column}"> </template>
    </a-table>
    <!-- <div style="font-size: 18px; font-weight: 800; margin-top: 10px">
      发票信息：
    </div>
    <a-table
      size="small"
      :dataSource="tableData3"
      :columns="columns4"
      bordered
      :pagination="false"
      row-key="id"
      :row-selection="{
        selectedRowKeys: submitDataProps.invoiceId,
        type: 'radio'
      }"
    >
      <template #bodyCell="{text, record, index, column}"> </template>
    </a-table> -->
    <div style="display: flex; line-height: 30px; margin-top: 10px">
      <div style="font-size: 18px; font-weight: 800">发票类型：</div>
      <a-radio-group
        v-model:value="submitDataProps.invoiceType"
        button-style="solid"
        disabled
      >
        <a-radio-button :value="item.type" v-for="item in invoiceType">{{
          item.name
        }}</a-radio-button>
      </a-radio-group>
    </div>
    <!-- 支付方式 -->
    <div
      style="
        padding: 14px 10px;
        background-color: #f3f3f3;
        display: flex;
        margin-top: 14px;
      "
    >
      <div style="font-size: 16px; font-weight: 800; color: #000">
        支付方式：
      </div>
      <a-radio-group
        v-model:value="formData.payWay"
        button-style="solid"
        @change="settleAccounts"
      >
        <a-radio-button :value="item.value" v-for="item in formData.payWays">{{
          item.name
        }}</a-radio-button>
      </a-radio-group>
    </div>
    <!-- 采购备注信息 -->
    <div
      style="padding: 14px 10px; background-color: #f3f3f3; margin-top: 14px"
    >
      <div
        style="
          font-size: 16px;
          font-weight: 800;
          color: #000;
          margin-bottom: 10px;
        "
      >
        采购备注信息：
      </div>
      <a-form :labelCol="{span: 4}" :model="formData" ref="formRef">
        <a-form-item label="订单号" name="customerOrderSN">
          <a-input v-model:value="formData.customerOrderSN" />
        </a-form-item>
        <a-form-item label="备注" name="customerRemark">
          <a-input v-model:value="formData.customerRemark" />
        </a-form-item>
        <a-form-item label="附件" name="attachment">
          <a
            :href="formData.attachment"
            target="_blank"
            v-if="formData.attachment"
            >查看附件</a
          >
          <a-button @click="upload" style="margin-left: 10px">上传</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!-- 优惠券 -->
    <div style="font-size: 18px; font-weight: 800; margin-top: 10px">
      选择优惠券：
    </div>
    <a-table
      size="small"
      :dataSource="formData.membersCoupons"
      :columns="columns5"
      bordered
      :pagination="false"
      row-key="id"
      :row-selection="{
        hideSelectAll: true,
        selectedRowKeys: membersCouponIdS,
        onChange: onSelectChange
      }"
    >
      <template #bodyCell="{text, record, index, column}"> </template>
    </a-table>
    <!-- 合计 -->
    <div
      style="padding: 14px 10px; background-color: #f3f3f3; margin-top: 14px"
    >
      <div
        style="
          font-size: 16px;
          font-weight: 800;
          color: #000;
          margin-bottom: 10px;
        "
      >
        合计
      </div>
      <div style="display: flex; justify-content: space-between">
        <div style="display: flex; justify-content: end">
          <div style="width: 330px; display: flex">
            <div style="width: 180px; text-align: right">
              <div>商品总件数：</div>
              <div>商品含税总额：</div>
              <div>税额：</div>
              <div>优惠卷优惠总额：</div>
            </div>
            <div style="width: 150px; text-align: right">
              <div>{{ formData.totalNumber }}</div>
              <div>￥{{ formData.amount }}</div>
              <div>￥{{ formData.tax }}</div>
              <div style="color: red">-￥{{ formData.discountAmount }}</div>
            </div>
          </div>
        </div>
        <div style="height: 88px">
          <div style="margin-top: 30px">
            <div
              style="text-align: right; margin-top: 4px; margin-bottom: 4px"
              v-if="!formData.isFreePostage"
            >
              还差{{
                arithmetic(
                  formData.freePostageFee,
                  formData.amount,
                  "subtract"
                )
              }}元，满足包邮金额
            </div>
            <div style="display: flex; justify-content: end; line-height: 28px">
              <div style="font-size: 16px">应付含税总额：</div>
              <div
                style="
                  font-size: 18px;
                  font-weight: 700;
                  color: red;
                  margin-left: 10px;
                  margin-right: 10px;
                "
              >
                ￥{{ formData.discountTotalAmount }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="display: flex; justify-content: end; margin-top: 10px">
      <a-button @click="cancel" style="margin-right: 10px">取消</a-button>
      <a-button type="primary" danger @click="submitOrder">提交订单</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, computed} from "vue";
import {trigerUpload, trigerUploadObs} from "@/utils/common";
import {arithmetic} from "@/utils/common";
import {
  getOrderSettlementInfo,
  surrogateCreateOrder
} from "@/api/orderManagement/behalfConsumer";
import dayjs from "dayjs";
import {message} from "ant-design-vue";
const tableLoading = ref<boolean>(false);
const emits = defineEmits(["statement", "update:data", "pressUndo", "cancel"]);
const props = defineProps({
  //收货地址
  takeList: {
    type: Array,
    default: []
  },
  //收票地址
  ticketList: {
    type: Array,
    default: []
  },
  //发票信息
  invoiceList: {
    type: Array,
    default: []
  },
  //结算查看信息
  data: {
    type: Object,
    default: {}
  },
  //结算提交信息
  submitData: {
    type: Object,
    default: {}
  }
});
const submitDataProps: any = computed({
  get() {
    return props.submitData;
  },
  set(value) {}
});
//已选择优惠券ID
const membersCouponIdS: any = ref([]);
const formData: any = computed({
  get() {
    try {
      props.data.totalNumber = 0;
      props.data.products.forEach((item) => {
        props.data.totalNumber += item.num;
        item.productImg = JSON.parse(item.productImg) || [];
      });
    } catch {
      props.data.products = [];
      props.data.totalNumber = 0;
    }
    membersCouponIdS.value = [props.data.membersCouponId];
    return props.data;
  },
  set(value) {}
});
const tableData1: any = computed({
  get() {
    return props.takeList.filter((item: any) => {
      return item.id == submitDataProps.value.receivingAddressId;
    });
  },
  set(value) {}
});
const tableData2: any = computed({
  get() {
    return props.ticketList.filter((item: any) => {
      return item.id == submitDataProps.value.invoiceAddressId;
    });
  },
  set(value) {}
});
// const tableData3: any = computed({
//   get() {
//     return props.invoiceList.filter((item: any) => {
//       return item.id == submitDataProps.value.invoiceId;
//     });
//   },
//   set(value) { }
// });
const invoiceType = ref([
  {name: "增值税专用票", type: "Z1"},
  {name: "增值税电子普通发票", type: "Z3"},
  {name: "数电增值税专票", type: "Z5"},
  {name: "数电增值税普票", type: "Z6"}
]);
const onSelectChange = (e) => {
  if (e.length > 1) {
    membersCouponIdS.value = [e[e.length - 1]];
  } else {
    membersCouponIdS.value = e;
  }
  settleAccounts();
};
const columns = ref<Array<object>>([
  {
    title: "商品信息",
    dataIndex: "productImg",
    align: "center",
    width: 400
  },
  {
    title: "含税单价(元)",
    dataIndex: "price",
    align: "center",
    width: 120
  },
  {
    title: "数量*单位",
    dataIndex: "num",
    align: "center",
    width: 120
  },
  {
    title: "含税小计(元)",
    dataIndex: "amount",
    align: "center",
    width: 120
  },
  {
    title: "客户物料号",
    dataIndex: "materialNum",
    align: "center",
    width: 120
  },
  {
    title: "客户物料名称",
    dataIndex: "materialName",
    align: "center",
    width: 120
  }
  // {
  //   title: "客户物料规格",
  //   dataIndex: "materialSpec",
  //   align: "center",
  //   width: 120
  // },
  // {
  //   title: "客户物料单位",
  //   dataIndex: "materialUnit",
  //   align: "center",
  //   width: 120
  // },
  // {
  //   title: "物料数量",
  //   dataIndex: "materialCount",
  //   align: "center",
  //   width: 120
  // }
]);
const columns2 = ref<Array<object>>([
  {
    title: "姓名",
    dataIndex: "name",
    align: "center",
    width: 120
  },
  {
    title: "电话",
    dataIndex: "phone",
    align: "center",
    width: 120
  },
  {
    title: "省",
    dataIndex: "province",
    align: "center",
    width: 80
  },
  {
    title: "市",
    dataIndex: "city",
    align: "center",
    width: 80
  },
  {
    title: "县",
    dataIndex: "county",
    align: "center",
    width: 80
  },
  {
    title: "详细地址",
    dataIndex: "address",
    align: "center",
    width: 150
  },
  {
    title: "邮箱地址",
    dataIndex: "email",
    align: "center",
    width: 100
  }
]);
const columns3 = ref<Array<object>>([
  {
    title: "姓名",
    dataIndex: "name",
    align: "center",
    width: 120
  },
  {
    title: "电话",
    dataIndex: "phone",
    align: "center",
    width: 120
  },
  {
    title: "省",
    dataIndex: "province",
    align: "center",
    width: 80
  },
  {
    title: "市",
    dataIndex: "city",
    align: "center",
    width: 80
  },
  {
    title: "县",
    dataIndex: "county",
    align: "center",
    width: 80
  },
  {
    title: "详细地址",
    dataIndex: "address",
    align: "center",
    width: 150
  },
  {
    title: "邮箱地址",
    dataIndex: "email",
    align: "center",
    width: 100
  }
]);
const columns4 = ref<Array<object>>([
  {
    title: "企业名称",
    dataIndex: "companyName",
    align: "center",
    width: 120
  },
  {
    title: "发票类型",
    dataIndex: "invoiceType",
    align: "center",
    width: 120,
    customRender: ({value}) => {
      if (value == 1) {
        return "增值税专用票";
      } else if (value == 2) {
        return "增值税专用电子发票";
      } else if (value == 3) {
        return "电子普通发票";
      } else if (value == 4) {
        return "普通发票";
      }
    }
  },
  {
    title: "发票抬头",
    dataIndex: "invoiceTitle",
    align: "center",
    width: 120
  },
  {
    title: "注册地址",
    dataIndex: "address",
    align: "center",
    width: 120
  },
  {
    title: "开户行",
    dataIndex: "bank",
    align: "center",
    width: 120
  },
  {
    title: "银行账号",
    dataIndex: "account",
    align: "center",
    width: 120
  },
  {
    title: "发票备注",
    dataIndex: "remark",
    align: "center",
    width: 120
  }
]);
const columns5 = ref<Array<object>>([
  {
    title: "优惠券名称",
    dataIndex: "name",
    align: "center",
    width: 120
  },
  {
    title: "优惠券折扣比例",
    dataIndex: "discount",
    align: "center",
    width: 120
  },
  {
    title: "开始时间",
    dataIndex: "beginDate",
    align: "center",
    width: 150,
    customRender: ({value}) => {
      return dayjs(value).format("YYYY-MM-DD");
    }
  },
  {
    title: "结束时间",
    dataIndex: "endDate",
    align: "center",
    width: 150,
    customRender: ({value}) => {
      return dayjs(value).format("YYYY-MM-DD");
    }
  },
  {
    title: "优惠券描述",
    dataIndex: "couponDescription",
    align: "center",
    width: 100
  }
]);
//上传附件
const upload = (): void => {
  trigerUpload().then((res: any) => {
    tableLoading.value = true;
    let files = res.target.files[0];
    trigerUploadObs(res)
      .then((data) => {
        formData.value.attachment = data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  });
};
//获取最新得结算信息
const settleAccounts = () => {
  tableLoading.value = true;
  let submitData = JSON.parse(JSON.stringify(formData.value));
  submitData.receivingAddressId =
    submitDataProps.value.receivingAddressId[0] || null;
  submitData.invoiceAddressId =
    submitDataProps.value.invoiceAddressId[0] || null;
  // submitData.invoiceId = submitDataProps.value.invoiceId[0] || null;
  submitData.invoiceType = submitDataProps.value.invoiceType || "";
  submitData.membersId = submitDataProps.value.membersId;
  submitData.bodyId = submitDataProps.value.bodyId;
  submitData.membersCouponId = membersCouponIdS.value[0] || null;
  submitData.shopProductInfos = submitData.products;
  getOrderSettlementInfo(submitData)
    .then((res) => {
      emits("update:data", res.data);
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
//返回到上一步操作
const pressUndo = () => {
  emits("pressUndo", 0);
};
//提交订单
const submitOrder = () => {
  if (formData.value.payWay || formData.value.payWay == 0) {
    // tableLoading.value=true;
    let submitData = JSON.parse(JSON.stringify(formData.value));
    submitData.receivingAddressId =
      submitDataProps.value.receivingAddressId[0] || null;
    submitData.invoiceAddressId =
      submitDataProps.value.invoiceAddressId[0] || null;
    // submitData.invoiceId = submitDataProps.value.invoiceId[0] || null;
    submitData.invoiceType = submitDataProps.value.invoiceType || "";
    submitData.membersId = submitDataProps.value.membersId;
    submitData.bodyId = submitDataProps.value.bodyId;
    submitData.membersCouponId = membersCouponIdS.value[0] || null;
    submitData.shopProductInfos = submitData.products;
    surrogateCreateOrder(submitData)
      .then((res) => {
        message.success("提交成功");
        emits("pressUndo", 2);
      })
      .finally(() => {
        tableLoading.value = false;
      });
  } else {
    message.error("请选择支付方式");
  }
};
//取消订单
const cancel = () => {
  emits("cancel");
};
defineExpose({
  tableLoading
});
</script>
<style lang="less" scoped></style>
